//
//  HMStatusViewModel.swift
//  webo
//
//  Created by apple on 2016/11/16.
//  Copyright © 2016年 apple. All rights reserved.
//

import UIKit

class HMStatusViewModel: NSObject {
    var iconURL: URL?
    
    var verifitedImage: UIImage?
    
    var mbRankImage: UIImage?
    
    var sourceText: String?
    var originalAttributedString: NSMutableAttributedString?
    var retWeetedAttributedString: NSMutableAttributedString?
    var rowHeight: CGFloat = 300

    //set方法赋值
    var status: HMStatusModel?{
        didSet{
            
            iconURL = URL(string: status?.user?.avatar_large ?? "")
            dealmyBbrankImage()
            dealWeiboVerifiredImage()
            sourceText = detaiSource(sr: status?.source ?? "")
            
            originalAttributedString = self.dealWeiboText(str: status?.text ?? "")
            retWeetedAttributedString = self.dealWeiboText(str: status?.retweeted_status?.text ?? "")
        }
        
    }

    func detaiSource(sr: String) -> String{
//<a href=\"http://app.weibo.com/t/feed/6vtZb0\" rel=\"nofollow\">iPhone 6s 土豪金</a>
        let start = ">"
        let end = "</a>"
        
        guard let starR = sr.range(of: start), let endR = sr.range(of: end) else {
            return "来自未来的你"
        }
        let rang = starR.upperBound..<endR.lowerBound
        let source = sr.substring(with: rang)
  
        return source
    }
    
    var timeText : String?{
        //        let ddd = "Sat Nov 19 19:53:06 +0800 2016"
//        let sharedDateformata = DateFormatter()
        
        sharedDateformata.dateFormat = "EEE MMM dd HH:mm:ss Z yyyy"
        sharedDateformata.locale = Locale(identifier: "en")
        
        guard  let sinceData = sharedDateformata.date(from: status?.created_at ?? "") else {
            return "走起"
        }
        let calender = Calendar.current
        let currentDate = Date()
        //        calender.dateComponents([], from: currentDate)
        let result = calender.dateComponents([.day,.year], from: sinceData, to: currentDate)
        if result.year == 0 {
            if calender.isDateInToday(sinceData) {
                let deatal = currentDate.timeIntervalSince(sinceData)
                if deatal < 60 {
                    return "刚刚"
                }else if(deatal < 3600){
                    return "\(Int(deatal/60))之前分钟"
                }else {
                    return "\(Int(deatal/3600))小时前"
                }
                
            }else if(calender.isDateInYesterday(sinceData)){
                sharedDateformata.dateFormat = "昨天 HH:mm";
                return sharedDateformata.string(from: sinceData)
            }else{
                sharedDateformata.dateFormat = "MM-dd HH:mm "
                return sharedDateformata.string(from: sinceData)
            }
        }else{
            
        sharedDateformata.dateFormat = "yyyy-MM-dd HH:mm"
            
        }
        
        return "ds";
    }
    
    
    var imgUrls: [HMPictuerInfo]?{
        if status?.retweeted_status == nil {
            return status?.pic_urls
        }
        return status?.retweeted_status?.pic_urls
    }
    
    
    func dealWeiboVerifiredImage(){
        let type = status?.user?.verified_type ?? -1
        switch type {
        case 0:
            verifitedImage = #imageLiteral(resourceName: "avatar_vip")
            
        case 2,3,5:
            verifitedImage = #imageLiteral(resourceName: "avatar_enterprise_vip")
            
        case 220:
            verifitedImage = #imageLiteral(resourceName: "avatar_grassroot")
            
        default:
            verifitedImage = nil
        }
    }
    
    func dealmyBbrankImage(){
        let mbrank = status?.user?.mbrank ?? 0
        if mbrank > 0 && mbrank < 7 {
            mbRankImage = UIImage(named: "common_icon_membership_level"+"\(mbrank)")
        }
        
    }
    
    //将微博正文/转发微博正文处理成富文本
    private func dealWeiboText(str: String) -> NSMutableAttributedString{
     /* []  表示一位* -   表示范围* ^ 在[]表示以什么开头* {a,b} 标识匹配范围以a开始 以b解
    * .*? 来表示匹配任意选项  通常用来标识忽略* ()  标识取出的意思* (.*?) 标识取出小括号中的任意项
     * \w 标识匹配所有的英文和中文 包括下划线( -)*/// + 向后匹配多次
        //1.实例化正则表达式对象  设置查找规则  频[x][xx],老师发现了x  xx同学上课看视频xy,老师发现了x
//        let pattern = "\\[.*?\\]"
//        let reguE = try! NSRegularExpression(pattern: pattern, options: [])

        //2. 通过规则在字符串中查找目标字符串 --> [NSTextCheckResult]   NSTextCheckingResult
        let resluts = reguE.matches(in: str, options: [], range: NSMakeRange(0, str.characters.count))
        //3.遍历结果集  获取表情字符串  ->> 倒序遍历
        
        //4. 将str转换可变的富文本
         let strm = NSMutableAttributedString(string: str)
        let font = UIFont.systemFont(ofSize: 15)
        let lineHeight = font.lineHeight
        
        for result in resluts.reversed() {
            let range = result.rangeAt(0)
            let sub = (str as NSString).substring(with: range)
            //4. 根据表情字符串在 表情数组中查找对应的表情模型(图片路径)
        if let em = HMEmoticonTools.sharedEmoticonTools.findEmoticon(chs:sub) {
            //查找到表情模型就开始后续的操作
            print(em)
            //5. 将图片转换成富文本   必须使用YYText提供的富文本的实例化方法
            //[NSMutableAttributedString yy_attachmentStringWithContent:image contentMode:UIViewContentModeCenter attachmentSize:image.size alignToFont:font alignment:YYTextVerticalAlignmentCenter]
            let image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
            
            let imgText = NSMutableAttributedString.yy_attachmentString(withContent: image, contentMode: .scaleAspectFit, attachmentSize: CGSize(width:lineHeight , height: lineHeight), alignTo: font, alignment: .center)
            //6. 将图片富文本替换到str对应的可变的富文本中
            //给富文本添加字体的属性
        strm.replaceCharacters(in: range, with: imgText)
            }
        }
        strm.addAttributes([NSFontAttributeName:font], range: NSRange(location: 0, length: strm.length))
//        addHighlighted(pattern: "@\\w+", strM: strm)
//        addHighlighted(pattern: "#.*?#", strM: strm)
//        addHighlighted(pattern: "(http|ftp|https):\\/\\/[\\w\\-_]+(\\.[\\w\\-_]+)+([\\w\\-\\.,@?^=%&amp;:/~\\+#]*[\\w\\-\\@?^=%&amp;/~\\+#])?", strM: strm)
        addHighlighted(regex: atSomeregex, strM: strm)
        addHighlighted(regex: topicRegex, strM: strm)
        addHighlighted(regex: urlRegex, strM: strm)

        return strm
    }
    
    private func addHighlighted(regex: NSRegularExpression,strM: NSMutableAttributedString){
//        let regex = try! NSRegularExpression(pattern: pattern, options: [])
       
        let str = strM.string
        let results = regex.matches(in: str, options: [], range: NSRange(location: 0, length: str.characters.count))
        for result in results {
            let range = result.rangeAt(0)
            strM.addAttributes([NSForegroundColorAttributeName:UIColor.orange], range: range)
            let border = YYTextBorder(fill: UIColor.red, cornerRadius: 3)
            let highlight = YYTextHighlight()
            highlight.setColor(UIColor.blue)
            highlight.setBackgroundBorder(border)
            strM.yy_setTextHighlight(highlight, range: range)
        }
        
        
        
    }
    
    
    
    
    
}
